// 导入的时候可以使用as来取别名
import { createStore, Store, useStore as useVuexStore } from 'vuex'

import login from './login/login'
import system from './system/system'
import dashboard from './analysis/dashboard'
import { IRootState, IStoreType } from './types'
import { getPageListData } from '@/service/main/system/system'

const store = createStore<IRootState>({
  state() {
    return {
      entireDepartment: [],
      entireRole: [],
      entireMenu: [],
    }
  },
  getters: {},
  mutations: {
    saveDepartment(state, departmentList) {
      state.entireDepartment = departmentList
    },
    saveRole(state, roleList) {
      state.entireRole = roleList
    },
    saveMenu(state, menuList) {
      state.entireMenu = menuList
    },
  },
  actions: {
    async getInitialListData({ commit }) {
      const departmentResult = await getPageListData('/department/list', { offset: 0, size: 100 })
      const { list: departmentList } = departmentResult.data

      const roleResult = await getPageListData('/role/list', { offset: 0, size: 100 })
      const { list: roleList } = roleResult.data

      const menuResult = await getPageListData('/menu/list', { offset: 0, size: 100 })
      const { list: menuList } = menuResult.data

      commit('saveDepartment', departmentList)
      commit('saveRole', roleList)
      commit('saveMenu', menuList)
    }
  },
  modules: {
    login,
    system,
    dashboard
  }
})

// 利用localStorage的数据加载vuex数据
export function loadStore() {
  store.dispatch('login/loadStoreAction')
}

// 解决vuex的store默认的any类型 没有类型检测(给store添加一个自定义<IStoreType>的类型)
export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
